home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12341 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Returning string from function (how?)
  5. Date: 30 Mar 1996 09:28 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <30MAR199609281747@erich.triumf.ca>
  9. References: <4jj4hh$m9n@news.xs4all.nl>
  10. NNTP-Posting-Host: erich.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4jj4hh$m9n@news.xs4all.nl>, jordan@xs4all.nl (Jordan) writes...
  14. >Hi all, i'm trying to get a string returned  from a function, but it's not
  15. >working as i planed.
  16.  
  17. >char s;
  18.  
  19. this reserves space for exactly one char.  If you want to declare space to
  20. store a string, you need something like:
  21.     char str[80]; /* allow space for the largest string you expect */
  22.             /* and have the input routine limit input to this */
  23.             /* size   */
  24.  
  25. >char get_str(void)
  26. >{
  27. >   int i;
  28. >   char ch, string;
  29. /* this should also be char string[80]; (or big enough...) */
  30. >   i=0;    
  31. >   printf("Enter a string: ");
  32. >   while((ch = getchar()) != '\n' && i < MAX)
  33. >      string[i++] = ch;
  34. >   string[i] = '\0';
  35. >   return string;
  36.  
  37. This returns (or would, if you had char string[80];) a pointer to an automatic
  38. variable, which will vanish when the function returns.  If you declare:
  39.     static char string[80];
  40. this would work.
  41.  
  42. I deleted a line "s = get_str();" above.  that should be replaced with:
  43.     strcpy(s, get_str());
  44. In C, you can't copy strings with an "=".
  45.  
  46. Perhaps a better technique would be to have the caller pass the string (and a
  47. size limit) to get_str() - have a look at fgets().
  48.  
  49. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  50. Internet: bennett@triumf.ca         | of one another only when one can be
  51. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  52. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  53. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  54. or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.